package com.fenghuajueli.libbasecoreui.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class FileUtils {

    public static void saveBitmapToPublic(Context context, Bitmap bitmap) throws IOException {
        OutputStream os;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            ContentValues values = new ContentValues();
            values.put(MediaStore.MediaColumns.DISPLAY_NAME, System.currentTimeMillis() + ".png");
            values.put(MediaStore.MediaColumns.MIME_TYPE, "image/*");
            values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);
            values.put(MediaStore.Video.Media.IS_PENDING, 1);
            ContentResolver contentResolver = context.getContentResolver();

            Uri imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            os = contentResolver.openOutputStream(imageUri);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
            values.clear();
            values.put(MediaStore.Video.Media.IS_PENDING, 0);
            contentResolver.update(imageUri, values, null, null);
        } else {
            String filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + File.separator + System.currentTimeMillis() + ".png";
            os = new FileOutputStream(filePath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
            os.flush();
            // 通知图库更新
            MediaStore.Images.Media.insertImage(context.getContentResolver(), filePath, new File(filePath).getName(), null);
            MediaScannerConnection.scanFile(context, new String[]{filePath}, new String[]{"image/png"}, null);
        }

        os.close();
    }
}
